package com.loveprogrammer.factory;

import com.alibaba.fastjson2.JSONArray;
import com.loveprogrammer.engine.enums.QualityEnum;
import com.loveprogrammer.factory.template.MonsterTemplate;
import com.loveprogrammer.model.Monster;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @ClassName MonsterFactory
 * @Description 怪物工厂
 * @Author admin
 * @Date 2024/2/18 9:53
 * @Version 1.0
 */
public class MonsterFactory {

    private static List<MonsterTemplate> monsterTemplates;

    private static Map<Integer,MonsterTemplate> monsterTemplateMap;

    // 初始化野怪模版
    static {
        try {
            // 读取配置文件，然后加载到weaponTemplates中
            ClassLoader classLoader = MonsterFactory.class.getClassLoader();
            InputStream inputStream = classLoader.getResourceAsStream("template/monster.json");

            assert inputStream != null;
            BufferedReader streamReader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder responseStrBuilder = new StringBuilder();

            String inputStr;
            while ((inputStr = streamReader.readLine()) != null)
                responseStrBuilder.append(inputStr);

            monsterTemplates = JSONArray.parseArray(responseStrBuilder.toString(), MonsterTemplate.class);
            monsterTemplateMap = monsterTemplates.stream().collect(Collectors.toMap(MonsterTemplate::getId, e->e));

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Monster createMonster(int monsterId, int level) {
        MonsterTemplate monsterTemplate = monsterTemplateMap.get(monsterId);
        QualityEnum qualityEnum = QualityEnum.白色;
        if(monsterTemplate.getQuality() > 5){
            qualityEnum = QualityEnum.暗金;
        }else if(monsterTemplate.getQuality() > 4){
            qualityEnum = QualityEnum.红色;
        }else if(monsterTemplate.getQuality() > 3){
            qualityEnum = QualityEnum.getById(new Random().nextInt(1)+4);
        }else{
            qualityEnum = QualityEnum.getById(new Random().nextInt(4)+1);
        }
        return createMonster(monsterTemplate,level,qualityEnum);
    }

    public static Monster createMonster(MonsterTemplate monsterTemplate, int level,
                                        QualityEnum qualityEnum){
        Monster monster = new Monster(monsterTemplate, qualityEnum);
        return monster.upLevel(level);
    }

    public static MonsterTemplate getById(int monsterId) {
        return monsterTemplateMap.get(monsterId);
    }

    public static void main(String[] args) {
        for (MonsterTemplate monsterTemplate : monsterTemplates) {
            System.out.println(monsterTemplate.toString());
        }
    }
}
